//
//  LocationHelper.m
//  test1
//
//  Created by Rip. on 16/2/26.
//  Copyright © 2016年 RipGSH. All rights reserved.
//

#import "LocationHelper.h"
#import "Marco.h"
@implementation LocationHelper

//+ (id)shareLocation
//{
//    static LocationHelper *locationHeper = nil;
//    dispatch_once_t once;
//    dispatch_once(&once, ^{
//        locationHeper = [[LocationHelper allocWithZone:NULL] init];
//    });
//    return locationHeper;
//}
//
//+ (id)allocWithZone:(struct _NSZone *)zone
//{
//    return [LocationHelper shareLocation];
//}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initLocationManager];
        [self initGeocoder];
        _locationDic = [NSDictionary dictionary];
        
    }
    return self;
}


- (void)initLocationManager
{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;
    }
    
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    //判断当前定位服务是否可用
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务不可用");
    }
    //判断当前定位是否授权
    //在plist文件中添加NSLocationWhenInUseUsageDescription，NSLocationAlwaysUsageDescription
    if (IOS_VERSION_8_OR_ABOVE) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            [_locationManager requestWhenInUseAuthorization];
        }
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //设置位置变化响应距离
    _locationManager.distanceFilter = 10.f;
    //设置定位精度
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    _locationManager.delegate = self;
    // NSLog(@"%d",[CLLocationManager authorizationStatus]);
    
}

- (void)initGeocoder
{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
}

#pragma mark -搜索地址
- (void)searchPlace:(NSString *)placeName
{
    [self geoCoder:placeName];
}

#pragma mark -开始定位
- (void)startLocation
{
    [_locationManager startUpdatingLocation];
}

#pragma mark -停止定位
- (void)stopLocation
{
    [_locationManager stopUpdatingLocation];
}

#pragma mark -地理编码（将地名转化成经纬度）
- (void)geoCoder:(NSString *)placeName;
{
    //地理编码方法 1.地名字符串 2.block 当地理编码成功后会调用此代码块 代码块参数1数组 数组中存放placeMark对象
    __block NSArray *array = nil;
    [_geocoder geocodeAddressString:placeName completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        array = placemarks;
        if (placemarks) {
            CLPlacemark *mark = placemarks[0];
            
            NSLog(@"mark.addressDictionary____%@",mark.addressDictionary);
            NSLog(@"mark.thoroughfare_____%@",mark.thoroughfare);
            
            [self.delegate addressInfoToView:mark.addressDictionary andCoordinate:_coordinate];
        }
    }];
}

#pragma mark -反地理编码（将经纬度转换成地名）
- (void)reverseCoder
{
    __block NSDictionary *dictionary = [NSDictionary dictionary];
    CLLocationDegrees lon = _coordinate.longitude;
    CLLocationDegrees lat = _coordinate.latitude;
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
       // NSLog(@"%@",placemarks);
        if (placemarks) {
            CLPlacemark *mark = placemarks[0];
            NSLog(@"mark.addressDictionary____%@",mark.addressDictionary);
            NSLog(@"mark.thoroughfare_____%@",mark.thoroughfare);
            dictionary = mark.addressDictionary;
            [self.delegate addressInfoToView:dictionary andCoordinate:_coordinate];
        }
    }];
    
}


#pragma mark -CLLocationManagerDelegate
//更新定位位置的协议方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //NSLog(@"locations.count== %ld_____%@",locations.count,locations);
    
    CLLocation *location1 = [locations lastObject];
    _coordinate = location1.coordinate;
    
    NSLog(@"经度：%f,纬度：%f",_coordinate.longitude,_coordinate.latitude);
    [self reverseCoder];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"错误：%@",error);
}

//更新定位方向的协议方法
- (void)locationManager:(CLLocationManager *)manager
       didUpdateHeading:(CLHeading *)newHeading
{
    
}

- (void)dealloc
{
    [self stopLocation];
}

@end
